package factory.one.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import factory.one.cache.CacheEnum;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author sk.z
 * 2023/7/26
 * 缓存配置
 **/
@Configuration
public class CacheConfig {

    @Bean
    @Primary
    public CacheManager cacheManager() {
        List<CaffeineCache> caffeineCaches = new ArrayList<>();
        for (CacheEnum c : CacheEnum.values()) {
            caffeineCaches.add(
                    new CaffeineCache(c.name(),
                            Caffeine.newBuilder()
                                    .recordStats()
                                    .expireAfterWrite(c.getTtl(), TimeUnit.SECONDS)
                                    .maximumSize(c.getMaxSize())
                                    .build()
                    )
            );
        }

        SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
        simpleCacheManager.setCaches(caffeineCaches);
        return simpleCacheManager;
    }

}
